import logging
import logging.handlers
import os
import datetime
import colorlog

log_folder = 'logs'
if not os.path.exists(log_folder):
    os.makedirs(log_folder)

log_filename = os.path.join(log_folder, datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S") + '.log')

# 创建一个自定义的日志格式
log_format = '%(log_color)s%(asctime)s - %(levelname)s - %(filename)s - line:%(lineno)d - %(message)s'

# 创建一个自定义的格式器
class CustomFormatter(logging.Formatter):
    def formatTime(self, record, datefmt=None):
        return datetime.datetime.fromtimestamp(record.created).strftime('%Y-%m-%d %H:%M:%S')

formatter = colorlog.ColoredFormatter(log_format)
formatter.formatTime = CustomFormatter().formatTime

# 创建一个日志记录器
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)

# 创建一个控制台处理器
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(formatter)
logger.addHandler(stream_handler)

# 创建一个文件处理器
file_handler = logging.handlers.TimedRotatingFileHandler(log_filename, when='midnight', interval=1, encoding='utf-8')

file_handler.suffix = "_%Y-%m-%d"
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)

# 设置不同日志级别的颜色
colorlog_default_log_colors = {
    'DEBUG': 'white',
    'INFO': 'green',
    'WARNING': 'yellow',
    'ERROR': 'red',
    'CRITICAL': 'bold_red',
}
colorlog.log_colors = colorlog_default_log_colors